<?php

namespace App\Http\Controllers;

use App\Parts;
use App\Product;
use App\ProductParts;
use App\StoreHouse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class StoreHouseController extends Controller
{
    public function index()
    {
        $list   = StoreHouse::orderby('id','asc')->paginate(10);
        return view('storehouse.index', compact('list'));
    }

    public function store(Request $request, $id = '')
    {
        $data = $request->only('name');
        $data1 = [
            'name' => $data['name'],
        ];

        try {
            DB::beginTransaction();
            if ($id) {
                StoreHouse::whereId($id)->update($data1);

            } else {

                StoreHouse::create($data1);
                /*                for ($i=0;$i<count($parts_name);$i++){
                                    $part_id[$i]=Parts::where('name',$parts_name[$i])->get()->id;

                                    $data2=[
                                        'product_id'=>$product->id,
                                        'parts_id' => $part_id[$i],
                                    ];
                                    ProductParts::create($data2);
                                }*/

            }
        } catch (\Exception $e) {
            DB::rollback();
            return redirect()->back()->with('rs', ['flag' => 'error', 'msg' => '编辑失败'.$e->getMessage()]);
        }

        DB::commit();
        return redirect('storehouse')->with('rs', ['flag' => 'success', 'msg' => '编辑成功']);
    }


    public function getInfo($id)
    {
        try {
            $oneProduct=StoreHouse::where('id',$id)->first();
            return response()->json(['rs' => 'true', 'data' => $oneProduct]);
        } catch (\Exception $e) {;
            return response()->json(['rs' => 'false', 'msg' => '错误的车型信息']);
        }
    }

    public function doDelete(Request $request)
    {
        try {
            $id = $request->get('_id');
            // 如果不存在ID,则返回错误
            if (!$id) {
                return response()->json(['rs' => 'false', 'msg' => '错误信息']);
            }

            $ids = explode(',', $id);

            StoreHouse::whereIn('id', $ids)->delete();

            return response()->json(['rs' => 'true', 'msg' => '操作成功']);
        } catch (\Exception $e) {;
            return response()->json(['rs' => 'false', 'msg' => '请刷新重新尝试']);
        }
    }

}
